package io.renren.sf.controller;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.Constant;
import io.renren.sf.entity.CbBookEditionEntity;
import io.renren.sf.service.CbBookEditionService;
import io.renren.sf.service.CbContentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.sf.entity.CbBookEntity;
import io.renren.sf.service.CbBookService;
import io.renren.common.utils.R;


/**
 * @author cyl_txw
 * @email cyl_txw@gmail.com
 * @date 2021-03-31 13:04:11
 */
@RestController
@RequestMapping("sf/cbbook")
public class CbBookController {
    @Autowired
    private CbBookService cbBookService;
    @Autowired
    private CbBookEditionService cbBookEditionService;

    /**
     * 通过bookId打资源包
     */
    @GetMapping("/createZip/{bookId}")
    public R createZip(@PathVariable("bookId") Long bookId) {
        try {
            String zipFile = cbBookService.createZip(bookId);
            if(!zipFile.contains(String.valueOf(bookId))){
                return R.error(zipFile);
            }
            CbBookEntity byId = cbBookService.getById(bookId);
            byId.setZipFile(zipFile);
            cbBookService.updateById(byId);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("资源包不完整，还需要添加数据");
        } finally {
            System.gc();
            System.runFinalization(); // 强制回收io流
            File zip = new File(Constant.Zip.YSB.getName() + bookId + ".zip");
            if(zip.exists()){
                // 删除压缩包
                zip.delete();
            }
            File dir = new File(Constant.Zip.PATH.getName());
            if (dir.exists()) {
                if (dir.isDirectory()) {
                    String[] children = dir.list();
                    // 递归删除目录中的子目录下
                    for (int i = 0; i < children.length; i++) {
                        (new File(dir, children[i])).delete();
                    }
                }
                dir.delete();
            }
        }
    }

    /**
     * 通过id获取editionId
     */
    @GetMapping("/getEditionIdById/{id}")
    public R getEditionIdById(@PathVariable("id") Long id){
        // 先看看是不是editionId
        CbBookEditionEntity byId = cbBookEditionService.getById(id);
        if(byId != null){
            // 说明是editionId
            return R.ok().put("editionId", id);
        }else {
            // 是bookId，通过它获取editionId
            Long editionId = cbBookService.getById(id).getEid();
            return R.ok().put("editionId", editionId);
        }
    }

    /**
     * 课本分页
     */
    @GetMapping("/list")
    public R bookPage(@RequestParam Map<String, Object> params) {
        Page<CbBookEntity> bookPage = cbBookService.getChapterByBookId(params);
        return R.ok().put("bookPage", bookPage);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    //@RequiresPermissions("sf:cbbook:info")
    public R info(@PathVariable("id") Long id) {
        CbBookEntity cbBook = cbBookService.getById(id);

        return R.ok().put("cbBook", cbBook);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    //@RequiresPermissions("sf:cbbook:save")
    public R save(@RequestBody CbBookEntity cbBook) {
        if(cbBookEditionService.getById(cbBook.getEid()).getIsClassify() == 1) {
            // 要分类就需要分类标签
            if(StringUtils.isEmpty(cbBook.getBookClassify())) {
                return R.error("软笔书分类不能为空");
            }
            if(StringUtils.isEmpty(cbBook.getBookTitle())) {
                return R.error("软笔书标签不能为空");
            }
        }
        cbBook.setCreatetime(new Date());
        cbBookService.save(cbBook);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    //@RequiresPermissions("sf:cbbook:update")
    public R update(@RequestBody CbBookEntity cbBook) {
        if(cbBookEditionService.getById(cbBook.getEid()).getIsClassify() == 1) {
            // 要分类就需要分类标签
            if(StringUtils.isEmpty(cbBook.getBookClassify())) {
                return R.error("软笔书分类不能为空");
            }
            if(StringUtils.isEmpty(cbBook.getBookTitle())) {
                return R.error("软笔书标签不能为空");
            }
        }
        cbBookService.updateById(cbBook);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    //@RequiresPermissions("sf:cbbook:delete")
    public R delete(@RequestBody Long[] ids) {
        /*List<CbContentsEntity> bid = cbContentsService.list(new QueryWrapper<CbContentsEntity>().eq("bid", ids[0]));
        if(!CollectionUtils.isEmpty(bid)){
            return R.error("该年级下还有目录等信息未删除");
        }*/
        cbBookService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 通过editionId获取对应书的集合
     */
    @GetMapping("/getBookListByEditionId/{editionId}")
    //@RequiresPermissions("sf:cbbook:delete")
    public R getBookListByEditionId(@PathVariable("editionId") Long editionId) {
        List<CbBookEntity> bookList = cbBookService.list(new QueryWrapper<CbBookEntity>().eq("eid", editionId));
        return R.ok().put("bookList", bookList);
    }

}
